package org.jeecg.basic.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.dynamic.datasource.annotation.DS;
import org.jeecg.basic.entity.MesPartDataCfg;
import org.jeecg.basic.entity.MesShiftCfg;
import org.jeecg.basic.service.IMesShiftCfgService;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.basic.entity.MesTestunitdetailCfg;
import org.jeecg.basic.entity.MesTestunitheadCfg;
import org.jeecg.basic.vo.MesTestunitheadCfgPage;
import org.jeecg.basic.service.IMesTestunitheadCfgService;
import org.jeecg.basic.service.IMesTestunitdetailCfgService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 产品样件配置
 * @Author: LiCY
 * @Date:   2024-11-27
 * @Version: V1.0
 */
@Api(tags="产品样件配置")
@RestController
@RequestMapping("/basic/mesTestunitheadCfg")
@Slf4j
public class MesTestunitheadCfgController extends JeecgController<MesTestunitheadCfg, IMesTestunitheadCfgService> {
	@Autowired
	private IMesTestunitheadCfgService mesTestunitheadCfgService;
	@Autowired
	private IMesTestunitdetailCfgService mesTestunitdetailCfgService;
	@Autowired
	private CommonAPI sysBaseApiImpl;
	
	/**
	 * 分页列表查询
	 *
	 * @param mesTestunitheadCfg
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "产品样件配置-分页列表查询")
	@ApiOperation(value="产品样件配置-分页列表查询", notes="产品样件配置-分页列表查询")
	@GetMapping(value = "/list")
	@DS("#header.his")
	public Result<IPage<MesTestunitheadCfg>> queryPageList(MesTestunitheadCfg mesTestunitheadCfg,
														   @RequestParam(name="partNo") String partNo,
														   @RequestParam(name="pnGroup", defaultValue="") String pnGroup,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<MesTestunitheadCfg> queryWrapper = QueryGenerator.initQueryWrapper(mesTestunitheadCfg, req.getParameterMap());
		queryWrapper.in("partNo", Arrays.asList(partNo,pnGroup));
		Page<MesTestunitheadCfg> page = new Page<MesTestunitheadCfg>(pageNo, pageSize);
		IPage<MesTestunitheadCfg> pageList = mesTestunitheadCfgService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param mesTestunitheadCfgPage
	 * @return
	 */
	@AutoLog(value = "产品样件配置-添加")
	@ApiOperation(value="产品样件配置-添加", notes="产品样件配置-添加")
    //@RequiresPermissions("org.jeecg:mes_testunithead_cfg:add")
	@PostMapping(value = "/add")
	@DS("#header.line")
	public Result<String> add(@RequestBody MesTestunitheadCfg mesTestunitheadCfg) {
		mesTestunitheadCfgService.saveMain(mesTestunitheadCfg);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param mesTestunitheadCfg
	 * @return
	 */
	@AutoLog(value = "产品样件配置-编辑")
	@ApiOperation(value="产品样件配置-编辑", notes="产品样件配置-编辑")
    //@RequiresPermissions("org.jeecg:mes_testunithead_cfg:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	@DS("#header.line")
	public Result<String> edit(@RequestBody MesTestunitheadCfg mesTestunitheadCfg) {
//		MesTestunitheadCfg mesTestunitheadCfg = new MesTestunitheadCfg();
//		BeanUtils.copyProperties(mesTestunitheadCfgPage, mesTestunitheadCfg);
//		MesTestunitheadCfg mesTestunitheadCfgEntity = mesTestunitheadCfgService.getById(mesTestunitheadCfgPage.getRecId());
//		if(mesTestunitheadCfgEntity==null) {
//			return Result.error("未找到对应数据");
//		}
		mesTestunitheadCfgService.updateById(mesTestunitheadCfg);
		return Result.OK("编辑成功!");
	}

	 /**
	  *  编辑
	  *
	  * @param list
	  * @return
	  */
	 @AutoLog(value = "产品样件配置-编辑")
	 @ApiOperation(value="产品样件配置-编辑", notes="产品样件配置-编辑")
	 //@RequiresPermissions("org.jeecg:mes_testunithead_cfg:edit")
	 @RequestMapping(value = "/detailAddOrEdit", method = {RequestMethod.PUT,RequestMethod.POST})
	 @DS("#header.line")
	 public Result<String> detailAddOrEdit(@RequestBody List<MesTestunitdetailCfg> list) {
		 Map<String, Object> hashMap = new HashMap<>();
		 hashMap.put("HEAD_ID", list.get(0).getHeadId());
		 mesTestunitdetailCfgService.removeByMap(hashMap);
		 list.forEach(item -> {
			 mesTestunitdetailCfgService.save(item);
				 });
		 return Result.OK("编辑成功!");
	 }
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "产品样件配置-通过id删除")
	@ApiOperation(value="产品样件配置-通过id删除", notes="产品样件配置-通过id删除")
    //@RequiresPermissions("org.jeecg:mes_testunithead_cfg:delete")
	@RequestMapping(value = "/delete")
	@DS("#header.his")
	public Result<String> delete(@RequestBody MesTestunitheadCfg mesTestunitheadCfg) {
		mesTestunitheadCfgService.delMain(mesTestunitheadCfg.getRecId());
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "产品样件配置-批量删除")
	@ApiOperation(value="产品样件配置-批量删除", notes="产品样件配置-批量删除")
    //@RequiresPermissions("org.jeecg:mes_testunithead_cfg:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	@DS("#header.his")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.mesTestunitheadCfgService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "产品样件配置-通过id查询")
	@ApiOperation(value="产品样件配置-通过id查询", notes="产品样件配置-通过id查询")
	@GetMapping(value = "/queryById")
	@DS("#header.his")
	public Result<MesTestunitheadCfg> queryById(@RequestParam(name="id",required=true) String id) {
		MesTestunitheadCfg mesTestunitheadCfg = mesTestunitheadCfgService.getById(id);
		if(mesTestunitheadCfg==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(mesTestunitheadCfg);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "样件点检项目配置通过主表ID查询")
	@ApiOperation(value="样件点检项目配置主表ID查询", notes="样件点检项目配置-通主表ID查询")
	@GetMapping(value = "/queryMesTestunitdetailCfgByMainId")
	@DS("#header.his")
	public Result<List<MesTestunitdetailCfg>> queryMesTestunitdetailCfgListByMainId(@RequestParam(name="id",required=true) String id) {
		List<MesTestunitdetailCfg> mesTestunitdetailCfgList = mesTestunitdetailCfgService.selectByMainId(id);
		return Result.OK(mesTestunitdetailCfgList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param mesTestunitheadCfg
    */
    //@RequiresPermissions("org.jeecg:mes_testunithead_cfg:exportXls")
    @RequestMapping(value = "/exportXls")
	@DS("#header.his")
    public ModelAndView exportXls(HttpServletRequest request, MesTestunitheadCfg mesTestunitheadCfg,String partNo,String pnGroup) {
		QueryWrapper<MesTestunitheadCfg> queryWrapper = new QueryWrapper<>();
		queryWrapper.in("PARTNO",partNo,pnGroup);
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		//配置选中数据查询条件
		String selections = request.getParameter("selections");
		if(oConvertUtils.isNotEmpty(selections)) {
			List<String> selectionList = Arrays.asList(selections.split(","));
			queryWrapper.in("id",selectionList);
		}
		//Step.2 获取导出数据
		List<MesTestunitheadCfg> mesTestunitheadCfgList = mesTestunitheadCfgService.list(queryWrapper);

		// Step.4 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, "产品样件配置列表");
		mv.addObject(NormalExcelConstants.CLASS, MesTestunitheadCfg.class);
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("产品样件配置数据", "导出人:"+sysUser.getRealname(), "产品样件配置"));
		mv.addObject(NormalExcelConstants.DATA_LIST, mesTestunitheadCfgList);
		return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("org.jeecg:mes_testunithead_cfg:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	@DS("#header.line")
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<MesTestunitheadCfg> list = ExcelImportUtil.importExcel(file.getInputStream(), MesTestunitheadCfg.class, params);
              for (MesTestunitheadCfg page : list) {
				  //获取当前产品序列号
				  String prefix = sysBaseApiImpl.getPrefix(page.getLine(), page.getOp(), page.getPartno());
				  Integer counterValue = sysBaseApiImpl.getCounterValue("boundary-"+page.getOp()+"-" + page.getPartno(),"0");
				  String format = String.format("%03d", counterValue);
				  page.setRecId(prefix+format);
				  mesTestunitheadCfgService.save(page);
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

}
